import { useCallback } from 'react';
import { formatDuration, formatFileSize } from '@/components/common/audioUpload/constants';

/**
 * 音频处理钩子
 * @param {Object} options - 配置选项
 * @param {Function} options.createBlobUrl - 创建Blob URL的函数
 * @param {Function} options.cleanupUnusedUrls - 清理未使用URL的函数
 * @param {Function} options.dispatch - Redux dispatch函数
 * @param {Function} options.setUploadedAudio - 设置已上传音频的Redux action
 * @param {Function} options.setCurrentAudio - 设置当前音频的Redux action
 */
export const useAudioHandler = ({ 
  createBlobUrl, 
  cleanupUnusedUrls, 
  dispatch, 
  setUploadedAudio, 
  setCurrentAudio 
}) => {
  // 处理音频上传
  const handleAudioUpload = useCallback(
    async ({ file, uploadKey, serverData }) => {
      try {
        // 获取文件实例
        const fileInstance = file.fileInstance || file;
        
        // 创建音频URL
        const audioUrl = createBlobUrl ? createBlobUrl(fileInstance) : URL.createObjectURL(fileInstance);

        // 创建音频元素获取时长等信息
        const audioElement = new Audio(audioUrl);
        
        // 返回Promise以便更好地处理异步操作
        return new Promise((resolve) => {
          audioElement.onloadedmetadata = () => {
            // 格式化时长
            const duration = formatDuration(audioElement.duration);

            // 构建音频信息对象
            const audioInfo = {
              url: audioUrl,
              name: fileInstance.name,
              duration: duration,
              size: formatFileSize(fileInstance.size),
              type: fileInstance.type,
              originalName: fileInstance.name,
              uploadTime: new Date().toISOString(),
              ...(serverData && { serverData })
            };

            // 如果提供了Redux相关函数，则更新Redux store
            if (dispatch && setUploadedAudio) {
              const storeKey = `dubbing_${uploadKey}`;
              dispatch(setUploadedAudio({ key: storeKey, audioInfo }));
            }

            // 如果提供了设置当前音频的函数，则设置为当前音频
            if (dispatch && setCurrentAudio) {
              dispatch(setCurrentAudio(audioInfo));
            }

            resolve(audioInfo);
          };

          // 处理加载错误
          audioElement.onerror = () => {
            console.error('音频加载失败');
            resolve({
              url: audioUrl,
              name: fileInstance.name,
              duration: '00:00',
              size: formatFileSize(fileInstance.size),
              type: fileInstance.type,
              originalName: fileInstance.name,
              uploadTime: new Date().toISOString(),
              hasError: true
            });
          };
        });
      } catch (error) {
        console.error('音频处理失败:', error);
        throw error;
      }
    },
    [createBlobUrl, cleanupUnusedUrls, dispatch, setUploadedAudio, setCurrentAudio]
  );

  // 清理音频资源
  const cleanupAudio = useCallback(
    (audioInfo) => {
      if (audioInfo && audioInfo.url) {
        if (cleanupUnusedUrls) {
          cleanupUnusedUrls(audioInfo.url);
        } else {
          URL.revokeObjectURL(audioInfo.url);
        }
      }
    },
    [cleanupUnusedUrls]
  );

  // 批量清理音频资源
  const cleanupAudioList = useCallback(
    (audioList = []) => {
      audioList.forEach(audioInfo => {
        cleanupAudio(audioInfo);
      });
    },
    [cleanupAudio]
  );

  return {
    handleAudioUpload,
    cleanupAudio,
    cleanupAudioList,
    formatDuration,
    formatFileSize
  };
};